<template>
  <div class="page-content">
    <div class="header">
      <div class="back" @click="goBack">
        <i class="iconfont-sys">&#xe866;</i>
        返回系统
      </div>
      <div class="right-btn">
        <p class="btn-item" @click="styleType = 1">
          <img src="../../assets/img/setting.png" class="setting-icon" />
          页面设置
        </p>
        <p style="margin-left: 36px" @click="handlePreview">保存并预览</p>
        <p style="margin-left: 36px" v-loading="saveLoading" @click="handleSave">保存</p>
      </div>
    </div>
    <div class="main-content">
      <div class="left" @click="styleType = 2">
        <div class="tabs-content">
          <el-tabs size="large" class="tabs" v-model="activePage" @change="handleClickPage">
            <el-tab-pane v-for="(item, index) in pageForm" :key="index" :label="item.name"
              :name="item.value"></el-tab-pane>
          </el-tabs>
        </div>

        <pc-question-content :content-data="currentPageData.showComponentList"></pc-question-content>
      </div>
      <div class="right">
        <div v-if="styleType === 1">
          <div class="page-set" v-if="styleType === 1">
            <div>
              <h3>基础设置</h3>
              <div class="line"></div>
              <el-form :model="currentPageData" label-position="left" label-width="auto">
                <el-form-item label="页面标题">
                  <el-input v-model="pageSet.pageName" placeholder="请输入页面标题"></el-input>
                </el-form-item>
                <el-form-item label="列表标题">
                  <el-input v-model="pageSet.name" placeholder="请输入列表标题"></el-input>
                </el-form-item>
                <el-form-item label="网站logo">
                  <div class="avatar-uploader" @click="handleChangeImage('logo')">
                    <el-image v-if="pageSet.logoUrl" :src="pageSet.logoUrl" class="avatar" fit="fill"></el-image>
                    <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                        <Plus />
                      </el-icon></i>
                    <div v-if="pageSet.logoUrl" class="mask">替换</div>
                    <el-icon v-if="pageSet.logoUrl" class="del-image" :size="20" @click.stop="handleDelLogoImg">
                      <CircleCloseFilled />
                    </el-icon>
                  </div>
                  <div>
                    <div>宽：1500px</div>
                    <div>高：525px</div>
                  </div>
                </el-form-item>
                <el-form-item label="网站背景">
                  <div class="avatar-uploader" @click="handleChangeImage('bgImageUrl')">
                    <el-image v-if="pageSet.bgImageUrl" :src="pageSet.bgImageUrl" class="avatar" fit="fill"></el-image>
                    <i v-else class="el-icon-plus avatar-uploader-icon"><el-icon>
                        <Plus />
                      </el-icon></i>
                    <div v-if="pageSet.bgImageUrl" class="mask">替换</div>
                    <el-icon v-if="pageSet.bgImageUrl" class="del-image" :size="20" @click.stop="handleDelBgImg">
                      <CircleCloseFilled />
                    </el-icon>
                  </div>
                  <div>
                    <div>宽：3840px</div>
                    <div>高：186px</div>
                  </div>
                </el-form-item>
                <el-form-item label="备注">
                  <el-input v-model="pageSet.remark" placeholder="请输入备注" type="textarea" :rows="3"></el-input>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
        <div v-if="styleType === 2">
          <pc-question-style :key="currentPageData.value" :title="currentPageData.name"
            :content-data="currentPageData.showComponentList" @update-data="handleUpdateData"></pc-question-style>
        </div>
      </div>
    </div>

    <el-dialog title="预览" v-model="showPreviewDialog" @close="showPreviewDialog = false" width="80%">
      <pc-question-content v-if="showPreviewDialog"
        :content-data="currentPageData.showComponentList"></pc-question-content>
    </el-dialog>

    <image-selected-dialog v-if="showImageChooseDialog" :show-image-choose-dialog="showImageChooseDialog"
      :single-type="true" :operation-type="false" @close-dialog="handleCloseImageDialog" />
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import PcQuestionContent from '@/views/decoration/diyComponents/PcContentComponent/PcQuestionContent.vue'
import PcQuestionStyle from '@/views/decoration/diyComponents/PcContentComponent/PcQuestionStyle.vue'
import cloneDeep from 'lodash/cloneDeep'
import {
  addDiyPage,
  editDiyPage,
  getPageDetail,
  getTemplateDetail
} from '@/api/materialManagement'
import { ref } from 'vue'
import { CircleCloseFilled, Plus } from '@element-plus/icons-vue'
import ImageSelectedDialog from '@/views/decoration/diyComponents/ImageSelectedDialog.vue'

const router = useRouter()
const route = useRoute()
const defaultData = {
  practiceCircleButton: {
    title: '顺序练习',
    subTitle: '0/1229',
    buttonText: '开始练习',
    bgColor: '#5BAAFF'
  },
  practiceHeader: {
    title: '全量考题 考前刷题',
    subTitle: '科目一全新考试题库，考前必刷，先练后考试'
  },
  examCircleButton: {
    title: '模拟考试',
    subTitle: '平均成绩0分',
    buttonText: '立即考试',
    bgColor: '#4edd2d'
  },
  examHeader: {
    title: '全量考题 考前刷题',
    subTitle: '科目四全新考试题库，考前必刷，先练后考试'
  },
  headerStyle: {
    titleStyle: { fontSize: 38, fontWeight: 'normal', color: '#000' },
    subTitleStyle: { fontSize: 23, color: '#999' }
  },
  imgStyle: {
    borderRadius: 12
  },
  practice_question_list: [
    {
      name: 'VIP课程',
      img: 'https://image.lutongjiakao.com/system/ed20cdb81fe141bc9511bc27eab8927a.png'
    },
    {
      name: '精选500道',
      img: 'https://image.lutongjiakao.com/system/ed20cdb81fe141bc9511bc27eab8927a.png'
    },
    {
      name: '图标技巧',
      img: 'https://image.lutongjiakao.com/system/ed20cdb81fe141bc9511bc27eab8927a.png'
    },
    {
      name: '专项练习',
      img: 'https://image.lutongjiakao.com/system/ed20cdb81fe141bc9511bc27eab8927a.png'
    },
    {
      name: '错题收藏',
      img: 'https://image.lutongjiakao.com/system/ed20cdb81fe141bc9511bc27eab8927a.png'
    }
  ],
  exam_question_list: [
    {
      name: 'VIP课程',
      img: 'https://image.lutongjiakao.com/system/ed20cdb81fe141bc9511bc27eab8927a.png'
    },
    {
      name: '精选500道',
      img: 'https://image.lutongjiakao.com/system/ed20cdb81fe141bc9511bc27eab8927a.png'
    },
    {
      name: '图标技巧',
      img: 'https://image.lutongjiakao.com/system/ed20cdb81fe141bc9511bc27eab8927a.png'
    },
    {
      name: '专项练习',
      img: 'https://image.lutongjiakao.com/system/ed20cdb81fe141bc9511bc27eab8927a.png'
    },
    {
      name: '错题收藏',
      img: 'https://image.lutongjiakao.com/system/ed20cdb81fe141bc9511bc27eab8927a.png'
    }
  ]
}

const pageSet = ref({
  name: '列表标题',
  pageName: '页面标题',
  remark: '',
  bgImageUrl: '',
  logoUrl: ''
})

const pageForm = ref([
  {
    value: 1,
    name: '科目一',
    showComponentList: {
      id: 1,
      ...cloneDeep(defaultData)
    }
  },
  {
    value: 4,
    name: '科目四',
    showComponentList: {
      id: 3,
      ...cloneDeep(defaultData)
    }
  },
  {
    value: 5,
    name: '满分学习',
    showComponentList: {
      id: 5,
      ...cloneDeep(defaultData)
    }
  },
  {
    value: 6,
    name: '注销重考',
    showComponentList: {
      id: 7,
      ...cloneDeep(defaultData)
    }
  }
])

const saveLoading = ref(false)
const showImageChooseDialog = ref(false)
const styleType = ref(1)
const addType = ref('')
const templateId = ref<any>('-1')
const editId = ref<any>()
const showPreviewDialog = ref(false)
const checkList = ref(pageForm.value.map((p) => p.value))

const activePage = ref(checkList.value[0])

const currentPageData = computed(() => {
  return pageForm.value.find((item) => item.value === activePage.value) ?? pageForm.value[0]
})

function goBack() {
  ElMessageBox.confirm('确定退出吗，如有改动请先保存再退出', '确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    router.push('/decoration/driving_school_decoration/pc_diy')
  })
}

function handleUpdateData(value: any) {
  currentPageData.value.showComponentList = value
}

function handleCloseImageDialog(val: any) {
  if (val) {
    if (addType.value === 'logo') {
      pageSet.value.logoUrl = val.fileUrl
    } else if (addType.value === 'bgImageUrl') {
      pageSet.value.bgImageUrl = val.fileUrl
    }
  }
  showImageChooseDialog.value = false
}

function handleDelLogoImg() {
  pageSet.value.logoUrl = ''
}

function handleDelBgImg() {
  pageSet.value.bgImageUrl = ''
}

function handleChangeImage(type: string) {
  showImageChooseDialog.value = true
  addType.value = type
}

function handleClickPage() { }

function handlePreview() {
  showPreviewDialog.value = true
}

function handleSave() {
  if (editId.value) {
    handleEditPage()
  } else {
    handleAddPage()
  }
}

async function handleAddPage() {
  try {
    saveLoading.value = true
    let obj: Record<string, any> = {
      name: pageSet.value.name,
      pageName: pageSet.value.pageName,
      remark: pageSet.value.remark,
      source: 1,
      pageType: 5,
      pageForm: JSON.stringify(pageSet.value),
      property: JSON.stringify(pageForm.value)
    }

    if (templateId.value !== '-1') {
      obj.templateId = templateId.value
      obj.source = 0
    }

    const res = await addDiyPage(obj)
    if (res.code === '00000') {
      ElMessage.success('新增成功')
      editId.value = res.data.id
      router.push(`/pcPageDiy/pcDesign?type=edit&id=${res.data.id}`)
      // goBack()
    }
  } catch (e) {
  } finally {
    saveLoading.value = false
  }
}

async function handleEditPage() {
  try {
    saveLoading.value = true
    let obj: Record<string, any> = {
      name: pageSet.value.name,
      pageName: pageSet.value.pageName,
      remark: pageSet.value.remark,
      pageType: 5,
      source: 1,
      pageForm: JSON.stringify(pageSet.value),
      property: JSON.stringify(pageForm.value)
    }

    if (templateId.value !== '-1') {
      obj.templateId = templateId.value
      obj.source = 0
    }

    const res = await editDiyPage(editId.value, obj)
    if (res.code === '00000') {
      ElMessage.success('编辑成功')
      // goBack()
    }
  } catch (e) {
  } finally {
    saveLoading.value = false
  }
}

async function getPageData(id: string) {
  const res = await getPageDetail(id)
  if (res.code === '00000') {
    templateId.value = res.data.templateId

    pageSet.value = JSON.parse(res.data.pageForm)
    let saveTab = JSON.parse(res.data.property)
    checkList.value = saveTab.map((item: any) => item.value)
    activePage.value = checkList.value[0]
    pageForm.value = saveTab
  } else {
    ElMessage.error(res.msg)
  }
}

async function getTemplateData(id: string) {
  const res = await getTemplateDetail(id)
  if (res.code === '00000' && res.data.property) {
    pageSet.value = JSON.parse(res.data.pageForm)
    pageForm.value = JSON.parse(res.data.property)
  } else {
    ElMessage.error(res.msg)
  }
}

onMounted(() => {
  let operaType = route.query.type
  if (operaType === 'edit') {
    editId.value = route.query.id
    getPageData(editId.value)
  } else if (operaType === 'add' && route.query.templateId) {
    templateId.value = route.query.templateId
    getTemplateData(templateId.value)
  }
})
</script>

<style scoped lang="scss">
.page-content {
  width: 100%;
  height: 100vh;
  overflow: hidden;

  .header {
    position: relative;
    width: 100%;
    height: 58px;
    background-color: #212c3d;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 26px;
    border-bottom: 1px solid #f5f5f5;
    box-sizing: border-box;

    .back {
      cursor: pointer;
      color: #fff;
      font-size: 14px;
    }

    .right-btn {
      display: flex;
      align-items: center;
      color: #fff;

      p {
        cursor: pointer;
        font-size: 14px;
      }

      .btn-item {
        display: flex;
        align-items: center;

        .setting-icon {
          width: 20px;
          height: 20px;
          margin-right: 3px;
          color: #fff;
        }
      }
    }
  }

  .main-content {
    display: flex;
    justify-content: space-between;
    width: 100%;
    height: calc(100% - 48px);

    .left {
      flex: 1 1 0%;
      min-width: 0;
      padding: 20px;
      box-sizing: border-box;
      background-color: #f4f5f8;

      ::v-deep(.el-tabs__item) {
        font-size: 18px;
        padding: 16px 24px;
      }

      ::v-deep(.el-tabs__nav-wrap) {
        height: 60px;
      }

      .tabs-content {
        display: flex;
        justify-content: center;
      }

      .tabs {
        margin-bottom: 30px;
      }
    }

    .right {
      min-width: 550px;
      background-color: #fff;
      overflow-y: auto;

      .page-set {
        padding: 20px;

        .line {
          width: 100%;
          height: 1px;
          background-color: #f5f7fa;
          margin: 20px 0;
        }

        .tip {
          font-size: 12px;
          color: #ccc;
          margin-left: 50px;
          margin-top: 10px;
          margin-bottom: 20px;
        }

        .type {
          display: flex;
          align-items: center;
          margin-bottom: 20px;

          .title {
            margin-right: 20px;
            font-size: 16px;
            font-weight: bold;
          }
        }

        .avatar-uploader {
          width: 70px;
          height: 70px;
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          cursor: pointer;
          position: relative;
          overflow: hidden;
          margin-right: 30px;
          text-align: center;

          .mask {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 24px;
            background-color: rgba(0, 0, 0, 0.6);
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: opacity 0.3s ease;
            color: #fff;
            font-size: 12px;
          }

          .del-image {
            display: none;
            position: absolute;
            top: 0;
            right: 0;
            cursor: pointer;
            color: #8c939d;
          }

          &:hover .mask {
            opacity: 1;
          }

          &:hover .del-image {
            display: block;
          }
        }

        .avatar-uploader-icon {
          font-size: 28px;
          color: #8c939d;
          width: 70px;
          height: 70px;
          line-height: 70px;
        }

        .avatar {
          width: 100%;
          height: 70px;
          display: block;
        }
      }
    }
  }
}
</style>
